package com.hm.uums.controller;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hm.common.annotation.Function;
import com.hm.common.api.ApiResult;
import com.hm.common.api.ApiStatus;
import com.hm.common.utils.JSONUtils;
import com.hm.common.utils.StringUtils;
import com.hm.uums.service.RoleService;
import com.hm.uums.utils.RequestStreamUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @author hwg
 *
 *         2020年12月18日
 */
@Api(tags = "3.角色接口")
@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {

	Logger logger = LoggerFactory.getLogger(RoleController.class);

	@Autowired
	private RoleService roleService;

	@ApiOperation("角色查询")
	@ApiImplicitParams({@ApiImplicitParam(name = "name", value = "角色名称", required = false, dataType = "String", paramType = "query"), @ApiImplicitParam(name = "status", value = "状态", required = false, dataType = "Integer", paramType = "query")})
	@GetMapping("/list")
	@Function(module = "uums", code = "uums.role.view", description = "角色查询")
	public ApiResult list(HttpServletRequest request) {
		String reqId = getReqId(request);
		Map<String, Object> params = getEmptyParam(request);
		params.put("name", request.getParameter("name"));
		params.put("status", request.getParameter("status"));

		List<Map<String, Object>> dataList = roleService.list(params);
		Map<String, Object> mData = toMapResult(dataList, dataList.size());
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "查询成功", request.getRequestURI(), mData);
	}

	@ApiOperation("设置角色状态")
	@ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "角色Id", required = true, dataType = "BigInteger", paramType = "query"), @ApiImplicitParam(name = "status", value = "角色状态", required = true, dataType = "Integer", paramType = "query")})
	@PutMapping("/status")
	@Function(module = "uums", code = "uums.role.edit", description = "设置角色状态")
	public ApiResult editRoleStatus(HttpServletRequest request) {
		String reqId = getReqId(request);

		String roleId = request.getParameter("roleId");
		String status = request.getParameter("status");

		if (StringUtils.isEmpty(roleId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(status)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色状态（status不能为空", request.getRequestURI(), null);
		}

		roleService.editRoleStatus(new BigInteger(roleId), Integer.parseInt(status));
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "设置成功", request.getRequestURI(), null);
	}

	@ApiOperation("删除角色")
	@ApiImplicitParams({@ApiImplicitParam(name = "roleId", value = "角色Id", required = true, dataType = "Long", paramType = "path")})
	@DeleteMapping("/{roleId}")
	@Function(module = "uums", code = "uums.role.del", description = "删除角色")
	public ApiResult delRole(HttpServletRequest request, @PathVariable(required = false) BigInteger roleId) {
		String reqId = getReqId(request);
		if (StringUtils.isEmpty(roleId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}

		roleService.delRole(roleId);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "删除成功", request.getRequestURI(), null);
	}

	@ApiOperation("获取角色")
	@GetMapping("/{roleId}")
	@Function(module = "uums", code = "uums.role.view", description = "获取角色")
	public ApiResult getRole(HttpServletRequest request, @PathVariable(required = false) BigInteger roleId) {
		String reqId = getReqId(request);
		if (StringUtils.isEmpty(roleId)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}

		Map<String, Object> dMap = roleService.getRole(roleId);
		if ((BigInteger) dMap.get("functionPId") != null) {//如果有上级角色，则获取上级角色的名字
			Map<String, Object> pRoleMap = roleService.getRole((BigInteger) dMap.get("functionPId"));
			dMap.put("functionPName", pRoleMap.get("name"));
		}
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "成功", request.getRequestURI(), dMap);
	}

	private Map<String, Object> parseRole(HttpServletRequest request) {
		String roleId = request.getParameter("roleId");
		String name = request.getParameter("name");
		String code = request.getParameter("code");
		String desc = request.getParameter("desc");
		String order = request.getParameter("order");

		Map<String, Object> dMap = new HashMap<String, Object>();
		dMap.put("roleId", StringUtils.isEmpty(roleId) ? null : new BigInteger(roleId));
		dMap.put("order", StringUtils.isEmpty(order) ? 0 : Integer.parseInt(order));
		dMap.put("name", name);
		dMap.put("code", code);
		dMap.put("desc", desc);
		return dMap;
	}

	@ApiOperation("新增角色")
	@PostMapping
	@Function(module = "uums", code = "uums.role.add", description = "新增角色")
	public ApiResult addRole(HttpServletRequest request) {
		String reqId = getReqId(request);

		Map<String, Object> dMap = parseRole(request);

		if (StringUtils.isEmpty(dMap.get("name"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色名称不能为空", request.getRequestURI(), null);
		}
		if (StringUtils.isEmpty(dMap.get("code"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色编号不能为空", request.getRequestURI(), null);
		}

		roleService.addRole(dMap);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "新增成功", request.getRequestURI(), null);
	}

	@ApiOperation("编辑角色")
	@PutMapping
	@Function(module = "uums", code = "uums.role.edit", description = "编辑角色")
	public ApiResult editRole(HttpServletRequest request) {
		String reqId = getReqId(request);
		Map<String, Object> dMap = parseRole(request);
		if (StringUtils.isEmpty(dMap.get("roleId"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}
		if (StringUtils.isEmpty(dMap.get("name"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色名称不能为空", request.getRequestURI(), null);
		}
		if (StringUtils.isEmpty(dMap.get("code"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色编号不能为空", request.getRequestURI(), null);
		}

		roleService.editRole(dMap);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "修改成功", request.getRequestURI(), null);
	}

	@ApiOperation("配置角色功能权限")
	@PostMapping("/function")
	@Function(module = "uums", code = "uums.role.cfg", description = "配置角色功能权限")
	public ApiResult editRoleFunction(HttpServletRequest request) {
		String reqId = getReqId(request);

		String reqBody = "";
		try {
			reqBody = RequestStreamUtils.readReqStream(request);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ApiResult.of(reqId, ApiStatus.STATUS_500, e.getMessage(), request.getRequestURI(), null);
		}

		if (StringUtils.isEmpty(reqBody)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "消息体为空", request.getRequestURI(), null);
		}

		Map<String, Object> dMap = null;
		try {
			dMap = JSONUtils.toObj(reqBody, Map.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ApiResult.of(reqId, ApiStatus.STATUS_500, e.getMessage(), request.getRequestURI(), null);
		}

		if (!(dMap.get("functions") instanceof List)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_801, request.getRequestURI());
		}

		if (StringUtils.isEmpty(dMap.get("roleId"))) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}

		BigInteger roleId = new BigInteger(StringUtils.toString(dMap.get("roleId")));
		List<BigInteger> functions = new ArrayList<BigInteger>();

		for (Object function : (List) dMap.get("functions")) {
			functions.add(new BigInteger(StringUtils.toString(function)));
		}

		roleService.editRoleFunction(roleId, functions);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "成功", request.getRequestURI(), null);
	}

	@ApiOperation("通过角色获取角色功能权限")
	@GetMapping("/function")
	@Function(module = "uums", code = "uums.role.view", description = "通过角色获取角色功能权限")
	public ApiResult functionList(HttpServletRequest request) {
		String reqId = getReqId(request);
		String roleIdStr = request.getParameter("roleId");

		if (StringUtils.isEmpty(roleIdStr)) {
			return ApiResult.of(reqId, ApiStatus.STATUS_800, "角色Id不能为空", request.getRequestURI(), null);
		}

		BigInteger roleId = new BigInteger(roleIdStr);
		List<Map<String, Object>> functions = roleService.functionList(roleId);
		Map<String, Object> mData = toMapResult(functions);
		return ApiResult.of(reqId, ApiStatus.STATUS_200, "查询成功", request.getRequestURI(), mData);
	}
}
